package service

import (
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"sensi/app/api/dto"
	"sensi/app/model"
	"sensi/common/sys/database"
)

func (s *Service) SupportDevice(ctx *gin.Context) (interface{}, error) {
	req := &dto.SupportDeviceReq{}
	if err := ctx.ShouldBindJSON(req); err != nil {
		return nil, err
	}

	list, err := s.deviceRepo.DevicesByPlatform(database.Instance(ctx), req.Platform)
	if err != nil {
		return nil, err
	}

	resp := struct {
		List []dto.SupportDeviceResp `json:"list"`
	}{
		List: make([]dto.SupportDeviceResp, 0),
	}
	for _, item := range list {
		resp.List = append(resp.List, dto.SupportDeviceResp{
			Platform:  item.Platform,
			Broadcast: item.Broadcast,
			Preview:   item.Preview,
		})
	}

	return resp, nil
}

func (s *Service) ListDevices(ctx *gin.Context) (interface{}, error) {
	list, err := s.deviceRepo.Devices(database.Instance(ctx))
	if err != nil {
		return nil, err
	}

	return list, nil
}

func (s *Service) AddDevice(ctx *gin.Context) (interface{}, error) {
	req := &dto.AddDeviceReq{}
	if err := ctx.ShouldBindJSON(req); err != nil {
		return nil, err
	}

	m := &model.Device{
		Platform:  req.Platform,
		Broadcast: req.Broadcast,
		Preview:   req.Preview,
	}

	if err := database.Instance(ctx).Save(m).Error; err != nil {
		return nil, err
	}

	return m, nil
}

func (s *Service) UpdateDevice(ctx *gin.Context) (interface{}, error) {
	req := &dto.UpdateDeviceReq{}
	if err := ctx.ShouldBindJSON(req); err != nil {
		return nil, err
	}
	m, err := s.deviceRepo.GetByID(database.Instance(ctx), req.ID)
	if err != nil {
		return nil, err
	}
	if m == nil {
		return nil, errors.New("empty dial")
	}

	m.Platform = req.Platform
	m.Preview = req.Preview
	m.Broadcast = req.Broadcast

	if err := database.Instance(ctx).Save(m).Error; err != nil {
		return nil, err
	}

	return m, nil
}

func (s *Service) DeleteDevice(ctx *gin.Context) (interface{}, error) {
	req := &dto.DeleteReq{}
	if err := ctx.ShouldBindJSON(req); err != nil {
		return nil, err
	}
	m, err := s.deviceRepo.GetByID(database.Instance(ctx), req.ID)
	if err != nil {
		return nil, err
	}
	if m == nil {
		return nil, errors.New("empty dial")
	}

	if err := database.Instance(ctx).Delete(m).Error; err != nil {
		return nil, err
	}

	return nil, nil
}
